package com.zhixiang.xaec.action.system;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zhixiang.core.command.QueryFilter;
import com.zhixiang.core.entity.TreeObj;
import com.zhixiang.core.util.JsonUtil;
import com.zhixiang.core.web.action.BaseAction;
import com.zhixiang.xaec.entity.system.Department;
import com.zhixiang.xaec.service.system.DepartmentService;


@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction
{

    private static final long serialVersionUID = -2845760327552708298L;

    private Department department;

    @Autowired
    private DepartmentService departmentService;

    public String save()
    {
        departmentService.saveDept(department);
        return SUCCESS;
    }

    public String get()
    {
        if (department != null && StringUtils.isNotEmpty(department.getDepId().toString()))
        {
            setResult(departmentService.get(department.getDepId()));
        }
        return SUCCESS;
    }

    public String list()
    {
        QueryFilter localQueryFilter = new QueryFilter(getRequest());
        List<Department> list = departmentService.getAll(localQueryFilter);
        setTotalCounts(localQueryFilter.getPagingBean().getTotalItems());
        setResult(list);
        return SUCCESS;
    }

    public void getAll()
    {
        // Department dept = departmentService.get(0L);
        Map<String,String> map = new HashMap<String,String>();
        map.put("Q_parentId_L_EQ", "1");
        List<TreeObj> list = departmentService.getTreeObj(1L,"depName",map);
        // List<TreeObj> treelist = new ArrayList<TreeObj>();
        // for (Department t : list) {
        // TreeObj obj = new TreeObj();
        // obj.setId(t.getDepId().toString());
        // obj.setText(t.getDepName());
        // obj.setLeaf(true);
        // treelist.add(obj);
        // }
        // 直接向页面输出字符串
        outJsonString(JsonUtil.object2Json(list));
//        outJsonString(new Gson().toJson(list));
    }

    public String delete()
    {
        try
        {
            String id = getRequest().getParameter("depId");
            departmentService.remove(new Long[]{Long.valueOf(id)});
        }
        catch (Exception e)
        {
            setSuccess(false);
            setMsg("部门删除失败");
        }
        return SUCCESS;
    }

    public Department getDepartment()
    {
        return department;
    }

    public void setDepartment(Department department)
    {
        this.department = department;
    }

}
